package com.ruoyi.common.config;

import cn.felord.AgentDetails;
import cn.felord.DefaultAgent;
import cn.felord.WeComTokenCacheable;
import cn.felord.api.WorkWeChatApi;
import cn.felord.callbacks.CallbackCrypto;
import cn.felord.callbacks.CallbackCryptoBuilder;
import com.ruoyi.common.base.biz.service.base.WeComCallbackEventService;
import com.ruoyi.common.base.biz.service.base.WecomCallbackSettingsService;
import com.ruoyi.common.config.cache.RedisWeComCacheable;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Wecom Sdk 配置
 *
 * @author dax
 * @since 2024/5/30
 */
@Configuration(proxyBeanMethods = false)
public class WeComSdkConfiguration {

    /**
     * 企微token，ticket 缓存中继，这里使用ehcache作为例子，你可以无缝替换为redis等缓存中间件
     * <p>
     * wecom-sdk 不提供具体的缓存实现，只做抽象，用什么用什么实现就是了，记得设置缓存时间7200
     *
     * @return the we com token cacheable
     */
    @Bean
    WeComTokenCacheable weComTokenCacheable() {
        return new RedisWeComCacheable();
    }


    /**
     * 初始化 企微API客户端，这个是平常我们发起调用的入口
     * <p>
     * 例子参见 test 测试包下的 SpringBootWecomSdkTests
     *
     * @param weComTokenCacheable the we com token cacheable
     * @return the work we chat api
     */
    @Bean
    WorkWeChatApi workWeChatApi(WeComTokenCacheable weComTokenCacheable) {
        return new WorkWeChatApi(weComTokenCacheable);
    }

    /**
     * 回调配置
     *
     * @param wecomCallbackEventService 统一消费回调数据
     * @param settingsService           统一加载回调配置
     * @return the callback crypto
     */
    @Bean
    public CallbackCrypto callbackCrypto(WeComCallbackEventService wecomCallbackEventService, WecomCallbackSettingsService settingsService) {
        return new CallbackCryptoBuilder(wecomCallbackEventService::handlerEventBody)
                .build(settingsService::loadCallbackSettings);
    }


    /**
     * agent配置
     * @param qyWxConfig
     * @return
     */
    @Bean
    public AgentDetails agentDetail(@Qualifier("qyWxConfig") QyWxConfig qyWxConfig) {
        return new DefaultAgent(qyWxConfig.getCorpid(), qyWxConfig.getCorpsecret(), qyWxConfig.getAgentid());
    }

}